package loginview;

import java.util.ArrayList;
import java.util.Random;

public class CodeUnit {
    private CodeUnit() {
    }

    public static String getCode() {
        ArrayList<Character> list = new ArrayList<>();
        //1.将大写字母和小写字母放到集合中
        for (int i = 0; i < 26; i++) {
            list.add((char) ('a' + i));
            list.add((char) ('A' + i));
        }

        //2.随机抽取4个字符
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < 4; i++) {
            int index = r.nextInt(list.size());
            char c = list.get(index);
            //把随机字符添加到sb中
            sb.append(c);
        }

        //3.把一个随机数字放到末尾
        int number = r.nextInt(10);
        sb.append(number);

        //4.调换数字，使数字出现在任意位置
        //把字符串变成字符数组，在数组中修改，再创建一个新的字符串
        char[] arr = sb.toString().toCharArray();

        int randomIndex = r.nextInt(arr.length);
        char temp = arr[arr.length - 1];
        arr[arr.length - 1] = arr[randomIndex];
        arr[randomIndex] = temp;

        return new String(arr);
    }
}
